const mosca = require('mosca');
const mysql=require('./conf/mysql').pool_dev;
const common=require('./conf/common').common;
const loger=require('./conf/log').logger;
const redis = require("./conf/redis").client;
//声明端口
const MqttServer = new mosca.Server({
    port: 8989
});
//监听redis 错误

redis.on("error", function (err) {
    loger.error(common.getThisFormatDate()+"-"+'redis error: ' + err);
});

// 监听客户端连接
MqttServer.on('clientConnected', function(client){
    //loger.info(client.id+'===connected');
   //console.log(client.id);
    if('clientsMachineUniqueId'!=client.id){
        mysql.getConnection(function(err,connection){
            connection.query('select * from pro_machine where code=?',[client.id],(error,results) => {
                if(error) throw error;
                if(!(results.length > 0)){
                    console.log(`没有找到机器`)
                    client.close(null);
                }
                connection.release()
            })
        })

    }
});

/**
 * 监听MQTT主题消息
 **/
MqttServer.on('published', function(packet, client) {
    //console.log(MqttServer.clients);
    var topic = packet.topic;
    loger.info('message-arrived--->','topic ='+topic+',message = '+ packet.payload.toString('hex'));
});

// 客户端断开连接
MqttServer.on('clientDisconnected', function(client){
    loger.info(client.id);
});
MqttServer.on('ready', function(){
    loger.info('mqtt is running...');
    //MqttServer.authenticate = authenticate;
});
process.on('uncaughtException', function (err) {
    loger.error(common.getThisFormatDate()+"-"+'Caught exception: ' + err);
});